const Service = require("egg").Service;
const OSS = require("ali-oss");
const crypto = require("crypto");
const path = require("path");

class OSSService extends Service {
  async upload(file) {
    const { ctx, app } = this;

    // 生成安全文件名
    const ext = path.extname(file.filename);
    const randomName = crypto.randomBytes(8).toString("hex");
    const filename = `${Date.now()}-${randomName}${ext}`;

    // 创建OSS客户端
    const client = new OSS(app.config.oss.client);

    try {
      // 上传文件
      const result = await client.put(filename, file.filepath, {
        headers: {
          "x-oss-object-acl": "public-read",
        },
      });

      return {
        url: result.url,
        name: filename,
      };
    } catch (err) {
      ctx.logger.error("OSS上传失败:", err);
      throw new Error("文件上传到OSS失败");
    } finally {
      // 清理临时文件
      await ctx.cleanupRequestFiles();
    }
  }
}

module.exports = OSSService;
